import turtle
import random

min_speed = 1
max_speed = 6
letter_list = []
speeds = []
points = []
letter_list_turtle = []
count = 10
game_over = False
score = 0
lower_chars="abcdefghijklmnopqrstuvwxyz"
# font and color
myfont=('宋体',50,'normal')
front_color='red'
back_ground_color='black'
word_color='yellow'
# screen
screen = turtle.Screen()
screen.setup(1000,800)
screen.title('打字游戏')
screen.bgcolor(back_ground_color)
screen.tracer(0,0)
# turtle
turtle.hideturtle()
turtle.up()
turtle.color(front_color)
# score_turtle
score_turtle = turtle.Turtle()
score_turtle.color(front_color)
score_turtle.up()
score_turtle.hideturtle()

def set_text(t,str1):
    return t.write(str1,align='center', font=myfont)

def draw_game_over():
    score_turtle.clear()
    turtle.goto(0,0)
    turtle.color(front_color)
    set_text(turtle,'游戏结束')
    turtle.goto(0,-150)
    turtle.color('orange')
    set_text(turtle,'你的分数是 {}'.format(score))
    for tt in letter_list_turtle:
        tt.clear()
    screen.update()

def draw_score():
    score_turtle.clear()
    score_turtle.goto(-200,200)
    set_text(score_turtle,'分数: {}'.format(score))
    screen.update()
    
def draw_letter_list():
    global game_over
    for i in range(len(letter_list)):
        letter_list_turtle[i].clear()
        letter_list_turtle[i].goto(points[i])
        set_text(letter_list_turtle[i],letter_list[i])
        points[i][1] -= speeds[i]
        if points[i][1]<-500:
            game_over = True
            draw_game_over()
            return
    screen.update()
    screen.ontimer(draw_letter_list,50)

def init_letter_turtles():
    for _ in range(count):
        letter_list_turtle.append(turtle.Turtle())
        while True:
            l = chr(ord('a')+random.randrange(26))
            if l not in letter_list:
                letter_list.append(l)
                break
        speeds.append(random.randint(min_speed,max_speed))
        points.append([random.randint(-450,450),500])
        
    for i in range(count):
        letter_list_turtle[i].hideturtle()
        letter_list_turtle[i].up()
        letter_list_turtle[i].color(word_color)

def update_data(c):
    global score
    if c in letter_list:
        score += 1
        k = letter_list.index(c)
        while True:
            l = chr(ord('a')+random.randrange(26))
            if l not in letter_list:
                letter_list[k] = l
                break            
        points[k] = [random.randint(-450,450),500]        
        speeds[k] = random.randint(min_speed,max_speed)
    else: score -= 1
    draw_score()
    
def esc():
    turtle.bye()

init_letter_turtles()
draw_score()   
draw_letter_list()

for key in lower_chars:
    screen.onkeypress(lambda key=key: update_data(key), key)
screen.onkeypress(lambda key=key: esc(), "Escape")

screen.listen()
screen.mainloop()
